<template>
  <div class="ebook-reader">
<!--    <div class="ebook-reader-mask"></div>-->
    <div class="read-wrapper">
      <div id="read"></div>
    </div>
  </div>
</template>

<script>
  import { ebookMixin } from '@/utils/mixin'
  import Epub from 'epubjs'
  global.ePuub = Epub
  export default {
    mixins: [ebookMixin],
    name: 'EbookReader',
    computed: {
    },
    mounted () {
      // http://192.168.0.45:8080/#/ebook/Laws|2015_Book_ProtectingTheRightsOfPeopleWit
      const fileName = this.$route.params.fileName.split('|').join('/')
      this.setFileName(fileName).then(() => {
        this.initEpub()
      })
    },
    methods: {
      initEpub (type, listener) {
        const url = 'http://192.168.0.45:8081/epub/' + this.fileName + '.epub'
        // console.log(url)
        this.book = new Epub(url)
        // console.log(this.book)
        this.setCurrentBook(this.book)
        this.rendition = this.book.renderTo('read', {
          width: innerWidth,
          height: innerHeight,
          method: 'default'
        })
        this.rendition.display()
        this.rendition.on('touchstart', event => {
          // console.log(event)
          this.touchStartX = event.changedTouches[0].clientX
          this.touchStartTime = event.timeStamp
        })
        this.rendition.on('touchend', event => {
          // console.log(event)
          const offsetX = event.changedTouches[0].clientX - this.touchStartX
          const time = event.timeStamp - this.touchStartTime
          // console.log(offsetX, time)
          if (time < 500 && offsetX > 40) {
            this.prevPage()
          } else if (time < 500 && offsetX < -40) {
            this.nextPage()
          } else {
            this.toggleTitleAndMenu()
          }
          event.preventDefault()
          event.stopPropagation()
        })
      },
      nextPage () {
        if (this.rendition) {
          this.rendition.next()
          this.hideTitleAndMenu()
        }
      },
      prevPage () {
        if (this.rendition) {
          this.rendition.prev()
          this.hideTitleAndMenu()
        }
      },
      toggleTitleAndMenu () {
        // console.log('toggle')
        if (this.menuVisible) {
          this.setSettingVisible(-1)
        }
        this.setMenuVisible(!this.menuVisible)
      },
      hideTitleAndMenu() {
        this.setMenuVisible(false)
        this.setSettingVisible(-1)
      }
    }
  }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  @import "../../assets/styles/global";

  .ebook-reader {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .ebook-reader-mask {
      position: absolute;
      z-index: 150;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
  }
</style>
